package com.movecar.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.model.FriendInfoBean;
import com.movecar.model.GroupBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.BitMapUtil;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 好友或陌生人-个人信息
 * 
 * @author Zhao.JQ
 * 
 */
public class FriendPersonalInfActivity extends Activity implements OnClickListener, OnCheckedChangeListener {

	private TextView user_nickname, remark_name, phone_num, title;
	private RelativeLayout shield, joined_activity, shared, remark, report;
	private LinearLayout user_info, shield_info;
	private CheckBox mCheckBox;
	private ImageView user_photo;
	private FriendInfoBean mInfoBean;
	private ImageLoader imageLoader = null;
	private String shareUserId;
	private Button add_friend;
	private CustomProgressDialog progressDialog = null;

	private boolean isOnLoad;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isOnLoad = true;
		setContentView(R.layout.friend_personal_information);
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		Intent intent = getIntent();
		shareUserId = intent.getStringExtra("shareUserId");
		initView();
	}

	private void initView() {
		user_info = (LinearLayout) findViewById(R.id.user_info);
		shield_info = (LinearLayout) findViewById(R.id.shield_info);
		user_nickname = (TextView) findViewById(R.id.user_nickname);
		remark_name = (TextView) findViewById(R.id.remark_name);
		phone_num = (TextView) findViewById(R.id.phone_num);
		user_photo = (ImageView) findViewById(R.id.user_photo);
		shield = (RelativeLayout) findViewById(R.id.shield);
		remark = (RelativeLayout) findViewById(R.id.remark);
		report = (RelativeLayout) findViewById(R.id.report);
		report.setOnClickListener(this);
		remark.setOnClickListener(this);
		mCheckBox = (CheckBox) findViewById(R.id.mCheckBox);
		mCheckBox.setOnCheckedChangeListener(this);
		joined_activity = (RelativeLayout) findViewById(R.id.joined_activity);
		joined_activity.setOnClickListener(this);
		shared = (RelativeLayout) findViewById(R.id.shared);
		shared.setOnClickListener(this);
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		add_friend = (Button) findViewById(R.id.btn_right);
		add_friend.setBackgroundResource(R.drawable.btn_add_friend);
		add_friend.setOnClickListener(this);
		title = (TextView) findViewById(R.id.title);
		startProgressDialog();
		queryInfo();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:

			finish();

			break;

		case R.id.btn_right:
			Intent intent = new Intent().setClass(this, AddFriendApplyActivity.class);
			intent.putExtra("friendId", shareUserId);
			startActivity(intent);
			break;

		case R.id.joined_activity:
			Intent next = new Intent(this, GroupActivity.class);
			next.putExtra("userId", shareUserId);
			startActivity(next);
			break;
		case R.id.shared:
			Intent i = new Intent(this, NewHomeActivity.class);
			i.putExtra("userId", shareUserId);
			i.putExtra("userName", mInfoBean.getNickname());
			startActivity(i);
			break;
		case R.id.remark:
			Intent remark = new Intent(this, AddFriendRemarkActivity.class);
			remark.putExtra("friendId", shareUserId);
			remark.putExtra("oldRemark", remark_name.getText().toString() == null ? "" : remark_name.getText()
					.toString());
			startActivityForResult(remark, 0);
			break;

		case R.id.report:
			if ("0".equals(mInfoBean.getReportFlag())) {
				reportShare(shareUserId);
			} else if ("1".equals(mInfoBean.getReportFlag())) {
				Alert.info(FriendPersonalInfActivity.this, "举报处理中，请耐心等待！");
			} else {

			}

			break;
		default:
			break;
		}

	}

	/**
	 * 屏蔽好友消息
	 */
	@SuppressWarnings("unchecked")
	private void screenFriend(String ischecked) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); //
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "screenFriendNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("friendId", shareUserId));
		params.add(new BasicNameValuePair("strFlag", ischecked));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				if ("0".equals(result)) {
					stopProgressDialog();
					Toast.makeText(getApplicationContext(), "操作成功", Toast.LENGTH_SHORT).show();

				} else {
					stopProgressDialog();
					Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
				}

			}

			@Override
			public void onFail(String exception) {

				Alert.error(FriendPersonalInfActivity.this, "与服务器连接失败，请检查网络");
			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	/**
	 * 获取用户信息
	 */
	@SuppressWarnings("unchecked")
	private void queryInfo() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryUserDetailNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("friendId", shareUserId));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mInfoBean = gson.fromJson(result, FriendInfoBean.class);
				} catch (Exception e) {
					return;
				}

				if ("".equals(mInfoBean.getError()) || null == mInfoBean.getError()) {
					if ("".equals(mInfoBean.getFail()) || null == mInfoBean.getFail()) {

						user_info.setVisibility(View.VISIBLE);

						if (TextUtils.isEmpty(mInfoBean.getIcon())) {
							user_photo.setImageBitmap(BitMapUtil.getRoundedCornerBitmap(BitMapUtil
									.drawableToBitmap(getResources().getDrawable(R.drawable.default_user_photo))));
						} else {
							if (mInfoBean.getIcon().contains("default")) {
								imageLoader.displayImage(AppConfig.HOST + mInfoBean.getIcon(), user_photo,
										Constants.image_display_options, AppConfig.animateListener);
							} else {
								imageLoader.displayImage(AppConfig.HOST + mInfoBean.getIcon(), user_photo,
										Constants.image_display_options_conner, AppConfig.animateListener);
							}
						}
						if ("0".equals(mInfoBean.getFriendFlag())) {
							remark.setVisibility(View.GONE);
						} else {
							remark.setVisibility(View.VISIBLE);
							remark_name.setText(mInfoBean.getRemarks());
						}
						user_nickname.setText(mInfoBean.getNickname());

						phone_num.setText(mInfoBean.getPhone());
						title.setText(mInfoBean.getNickname());
						if ("1".equals(mInfoBean.getFriendFlag())) {
							shield_info.setVisibility(View.VISIBLE);
							mCheckBox.setVisibility(View.VISIBLE);
						} else {
							add_friend.setVisibility(View.VISIBLE);
							add_friend.setOnClickListener(FriendPersonalInfActivity.this);
						}
						if ("1".equals(mInfoBean.getScreenFlag())) {
							mCheckBox.setChecked(true);
						} else {
							mCheckBox.setChecked(false);

						}
						isOnLoad = false;
					} else {
						stopProgressDialog();
						Toast.makeText(getApplicationContext(), mInfoBean.getFail(), Toast.LENGTH_SHORT).show();
					}
				} else {
					stopProgressDialog();
					Toast.makeText(getApplicationContext(), mInfoBean.getError(), Toast.LENGTH_SHORT).show();
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(FriendPersonalInfActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				queryInfo();
			}
		}

	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/**
	 * 好友举报
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void reportShare(String friendId) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "reportFriendNew2")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("friendId", friendId));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;

				if ("0".equals(result)) {
					mInfoBean.setReportFlag("1");
					Alert.info(FriendPersonalInfActivity.this, "举报成功，等待处理！");
				} else {
					stopProgressDialog();
					Alert.error(FriendPersonalInfActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(FriendPersonalInfActivity.this, "与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {

		case R.id.mCheckBox:
			if (!isOnLoad) {
				if (isChecked) {
					screenFriend("1");
				} else {
					screenFriend("0");
				}
			}

			break;
		}
	}
}
